import React from 'react';
import ReactDOM from 'react-dom';
import {Machine,interpret,assign,useService} from './xstate';
//import {useService} from '@xstate/react';
//实现开关的应用
const todosMachine = Machine({
  id:'todos',//待办事项
  initial:'ready',//初始状态
  //context里存放着数据 不同的状态会切换或者说改变上下文 context
  context:{
    text:'',
    todoList:["吃饭"]
  },
  states:{
    ready:{
      on:{//当在ready状态下发送CHANGE动作的话，会执actions里面定义的动作
        "CHANGE":{
          actions:[
            assign({
              text:(context,event)=>event.value
            })
          ]
        },
        "ADD_TODO":{
          actions:[
            assign({
              text:'',
              todoList:context=>[...context.todoList,context.text]
            })
          ]
        }
      }
    }
  }
})
//当状态发生变更的时候，会执行回调
let todosService = interpret(todosMachine).onTransition(state=>{
  console.log(state.context);//上下文对象
});

/* 
todosService.start();//启动状态机 ready
todosService.send({type:'CHANGE',value:'睡觉'});
todosService.send({type:'ADD_TODO'});
*/
todosService.start();
function TodoApp(){
  let [state,send] = useService(todosService);
  const {context:{text,todoList}} = state;
  return (
    <div>
      <input value={text} onChange={(event)=>send({type:'CHANGE',value:event.target.value})}/>
      <button onClick={()=>{send({type:'ADD_TODO'})}}>增加</button>
      <ul>
        {
          todoList.map(item=><li key={item}>{item}</li>)
        }
      </ul>
    </div>
  )
}

ReactDOM.render(<TodoApp/>,document.getElementById('root'));